<template>
    <div class="create-edit-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="110px">
                <el-form-item label="集成者" prop="integratorNo" class="integrator-box">
                    <el-select v-model="formData.integratorNo" placeholder="请选择集成者" clearable>
                        <el-option
                            v-for="(item, i) in integratorList"
                            :label="item.integratorName"
                            :key="i"
                            :value="item.integratorNo"
                        />
                    </el-select>
                    <el-button link type="primary" @click="setIntegrator">维护集成者</el-button>
                </el-form-item>
                <el-form-item label="标识符" required>
                    <el-input v-model="formData.integratorNo" disabled placeholder="自动带入"></el-input>
                </el-form-item>
                <el-form-item label="消息类型" prop="messageTypes">
                    <el-select
                        v-model="formData.messageTypes"
                        placeholder="请选择消息类型"
                        :multiple="isEdit() ? false : true"
                        collapse-tags
                        collapse-tags-tooltip
                    >
                        <el-option
                            v-for="(item, i) in classifyList"
                            :label="item.typeName"
                            :key="i"
                            :value="item.typeNo"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="集成范围" prop="integrationScope">
                    <el-radio-group v-model="formData.integrationScope">
                        <el-radio v-for="(value, key) in IntegrationScope" :value="key" :key="key">{{
                            value
                        }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="描述" style="width: 100%; margin-left: 0">
                    <el-input
                        v-model="formData.messageDesc"
                        type="textarea"
                        maxlength="200"
                        show-word-limit
                        placeholder="请输入描述"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { messageIntegrationService, messageClassifyService } from '@great/services';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { showPopupBox, type PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';
import { IntegrationScope } from '@/utils/constant';
import SetIntegratorModal from './SetIntegratorModal.vue';

interface IProps extends PopupBoxProps {
    row?: Record<string, any>;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();
const router = useRouter();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '新建消息集成',
    width: 900,
    detail: undefined
});

const formData = reactive<any>({
    id: undefined,
    integratorNo: '',
    messageTypes: [],
    integrationScope: 'ALL',
    messageDesc: ''
});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules<any>>({
    integratorNo: [{ required: true, message: '请选择集成者', trigger: ['change', 'blur'] }],
    messageTypes: [{ required: true, message: '请选择消息类型', trigger: ['change', 'blur'] }],
    integrationScope: [{ required: true, message: '请选择集成范围', trigger: ['change', 'blur'] }]
});
const integratorList = ref<
    Array<{
        integratorName: string;
        integratorNo: string;
    }>
>([]);
const classifyList = ref<
    Array<{
        typeName: string;
        typeNo: string;
    }>
>([]);
// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};
const buildForm = () => {
    let tergetData = JSON.parse(JSON.stringify(formData));
    if (isEdit()) {
        tergetData.messageTypeNo = tergetData.messageTypes;
        delete tergetData.messageTypes;
    }
    return tergetData;
};
// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return messageIntegrationService[isEdit() ? 'edit' : 'create'](buildForm());
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: `${isEdit() ? '修改' : '创建'}成功！`,
                type: 'success'
            });
            closeDialog();
        }
    }
);

// 表单提交
const submitForm = () => {
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};
const getClassify = async () => {
    const res: any = await messageClassifyService.getList({
        enable: true
    });
    classifyList.value = res.data;
};
const getIntegratorList = async () => {
    const res: any = await messageIntegrationService.getIntegratorList();
    integratorList.value = res.data;
};
// 维护集成者
const setIntegrator = () => {
    let integratorObj;
    if (formData.integratorNo) {
        integratorObj = integratorList.value.find(item => item.integratorNo === formData.integratorNo);
    }
    showPopupBox(SetIntegratorModal, {
        row: formData.integratorNo ? integratorObj : undefined,
        callBack: getIntegratorList
    });
};
//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};

// 打开弹框
const openDialog = () => {
    if (props.row) {
        dialog.title = '修改消息集成';
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row?.id;
        Object.keys(formData).forEach(key => {
            if (key === 'messageTypes') {
                formData[key] = props.row?.messageTypeNo;
            } else {
                formData[key] = props.row?.[key];
            }
        });
    } else {
        delete formData.id;
    }
};

const init = () => {
    getIntegratorList();
    getClassify();
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.create-edit-modal-wrapper {
    .el-form {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
            width: calc((100% - 10px) / 2);
        }
        .el-form-item:nth-child(even) {
            margin-left: 10px;
        }
        :deep(.integrator-box) {
            .el-form-item__content {
                display: flex;
                .el-select {
                    flex: 1;
                    margin-right: 5px;
                }
            }
        }
    }
}
</style>
